import React, { useState, useEffect, useCallback } from 'react';
import { connect } from 'umi';
import { Form, Card, DatePicker, Select, Table, message, Icon } from 'antd';

import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { AdvancedSearch } from '@/components';
import Pagination from '@/components/Pagination';
import { isSuccess } from '@/utils/request';
import { SearchInput } from '@/components/UserForm';
import { hrOverviewRecheck } from '@/services/salaryManage/salaryCalculate';
import { queryEmployeeList } from '@/services/salaryManage/salaryCommon';
import { withRoutePage } from '@/utils/enhanceUtils';

import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { pageTabProps } from '@/pages/SalaryManage/utils';
import { OrganizationNameHead } from '@/pages/SalaryManage/components/OrganizationName';

const { RangePicker, MonthPicker } = DatePicker;
const { Option } = Select;
const Page = ({ form, user, location }) => {
    const { getFieldDecorator } = form;

    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10
    });

    const { organizationCode } = location.query
    const [dataSource, setDataSource] = useState([]);
    const [loading, setLoading] = useState(false);
    const [busiUnitMaps, setBusiUnitMaps] = useState({});
    const [busiTypeMaps, setBusiTypeMaps] = useState({});
    const [financeOperateTypeMaps, setFinanceOperateTypeMaps] = useState({});
    const [hrOperateTypeMaps, setHrOperateTypeMaps] = useState({});
    const [operateTypeMaps, setOperateTypeMaps] = useState({});

    const columns = [
        {
            dataIndex: 'operateDateTime',
            title: '操作时间',
            width: '18%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'operateUser',
            title: '操作人',
            width: '10%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'busiTypeName',
            title: '业务类型',
            width: '10%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'operateTypeName',
            title: '操作类型',
            width: '13%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'salaryPayrollYearMonth',
            title: '薪资月份',
            width: '10%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'busiUnitName',
            title: '页面类型',
            width: '10%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'operateObject',
            title: '操作对象',
            width: '10%',
            render: text => <EmptyPlaceHolder value={text} />
        },
        {
            dataIndex: 'content',
            title: '操作内容描述',
            render(text) {
                return (
                    <span
                        style={{
                            display: 'inline-block',
                            whiteSpace: 'break-spaces',
                            wordBreak: 'break-all'
                        }}
                    >
                        <EmptyPlaceHolder value={text} />
                    </span>
                );
            }
        }
    ];

    /**
     * 查询
     */
    const search = useCallback(
        async pg => {
            setLoading(true);

            const formValues = form.getFieldsValue();
            const pageVo = pg || { ...pagination, current: 1 };
            const postData = {
                ...formValues,
                organizationCode: organizationCode || user.companyId,
                operateDateBegin: formValues?.time?.[0] ? formValues.time[0].format('YYYY-MM-DD') : null,
                operateDateEnd: formValues?.time?.[1] ? formValues.time[1].format('YYYY-MM-DD') : null,
                year: formValues?.period ? formValues.period.format('YYYY') : null,
                month: formValues?.period ? formValues.period.format('MM') : null,
                operateObject: formValues.operateObject ? Object.values(formValues.operateObject).join(',') : '',
                page: {
                    pageNo: pageVo.current || 1,
                    pageSize: pageVo.pageSize || 10
                }
            };
            const response = await hrOverviewRecheck.querySalaryRecheckLog(postData);
            if (!isSuccess(response)) {
                message.error(response.msg);
                setLoading(false);
                return;
            }

            setLoading(false);

            const { pageSize, total, pageNo: current, rows } = response.data;

            setPagination({
                ...pagination,
                pageSize: pageSize || 10,
                current: current || 1,
                total
            });
            setDataSource(rows);
        },
        [form, pagination]
    );

    const handleReset = () => {
        form.resetFields();
    };

    const tablePageChange = ({ current, pageSize }) => {
        search({
            ...pagination,
            current: current || pagination.current,
            pageSize: pageSize || pagination.pageSize
        });
    };

    const busiTypeChangeFn = value => {
        form.resetFields('operateType');
        switch (value) {
            case '1':
                setOperateTypeMaps(hrOperateTypeMaps);
                break;
            case '2':
                setOperateTypeMaps(financeOperateTypeMaps);
                break;
            default:
                setOperateTypeMaps(
                    Object.assign(
                        JSON.parse(JSON.stringify(hrOperateTypeMaps)),
                        JSON.parse(JSON.stringify(financeOperateTypeMaps))
                    )
                );
                break;
        }
    };

    useEffect(() => {
        const initPage = async () => {
            const [response] = await Promise.all([
                // 获取查询枚举数据
                hrOverviewRecheck.querySalaryRecheckLogEnum()
            ]);

            setLoading(false);
            if (!isSuccess(response)) {
                message.error(response.msg);
                return;
            }

            const { busiTypeMap, busiUnitMap, financeOperateTypeMap, hrOperateTypeMap } = response.data;

            setBusiTypeMaps(busiTypeMap);
            setBusiUnitMaps(busiUnitMap);
            setFinanceOperateTypeMaps(financeOperateTypeMap);
            setHrOperateTypeMaps(hrOperateTypeMap);
            setOperateTypeMaps(
                Object.assign(
                    JSON.parse(JSON.stringify(hrOperateTypeMap)),
                    JSON.parse(JSON.stringify(financeOperateTypeMap))
                )
            );
        };
        initPage().then(() => search());
    }, []);

    return (
        <PageHeaderWrapper type="success">
            <Card
                bordered={false}
                title="操作日志"
                {...pageTabProps()}
                extra={<OrganizationNameHead organizationCode={organizationCode} />}
            >
                <AdvancedSearch form={form} onSubmit={search} onReset={handleReset}>
                    <Form.Item label="操作时间">
                        {getFieldDecorator('time', {})(<RangePicker placeholder="开始时间-结束时间" />)}
                    </Form.Item>
                    <Form.Item label="操作人">
                        {getFieldDecorator(
                            'operateUser',
                            {}
                        )(
                            <SearchInput
                                params={{
                                    organizationCode
                                }}
                                getData={async params => {
                                    if (!params.organizationCode) {
                                        return [];
                                    }
                                    const employeeResponse = await hrOverviewRecheck.querySalaryOperateEmployeeList({
                                        organizationCode: params.organizationCode
                                    });
                                    return isSuccess(employeeResponse) ? employeeResponse.data || [] : [];
                                }}
                                selectProps={{
                                    placeholder: '请输入员工姓名',
                                    allowClear: true
                                }}
                                fieldsName={{
                                    value: 'employeeCode',
                                    title: 'name'
                                }}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="业务类型">
                        {getFieldDecorator('busiType', {
                            initialValue: null
                        })(
                            <Select onChange={busiTypeChangeFn}>
                                <Option value={null}>全部</Option>
                                {busiTypeMaps &&
                                    Object.entries(busiTypeMaps).map(item => (
                                        <Option key={item[0]} value={item[0]}>
                                            {item[1]}
                                        </Option>
                                    ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="操作类型">
                        {getFieldDecorator('operateType', {
                            initialValue: null
                        })(
                            <Select>
                                <Option value={null}>全部</Option>
                                {operateTypeMaps &&
                                    Object.entries(operateTypeMaps).map(item => (
                                        <Option key={item[0]} value={item[0]}>
                                            {item[1]}
                                        </Option>
                                    ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="薪资月份">
                        {getFieldDecorator('period', {
                            initialValue: null
                        })(<MonthPicker suffixIcon={<Icon type="down" />} allowClear />)}
                    </Form.Item>
                    <Form.Item label="页面类型">
                        {getFieldDecorator('busiUnit', {
                            initialValue: null
                        })(
                            <Select>
                                <Option value={null}>全部</Option>
                                {busiUnitMaps &&
                                    Object.entries(busiUnitMaps).map(enumItem => (
                                        <Option key={enumItem[0]} value={enumItem[0]}>
                                            {enumItem[1]}
                                        </Option>
                                    ))}
                            </Select>
                        )}
                    </Form.Item>
                    <Form.Item label="操作对象">
                        {getFieldDecorator(
                            'operateObject',
                            {}
                        )(
                            <SearchInput
                                getData={async () => {
                                    const employeeResponse = await queryEmployeeList({
                                        organizationCode: organizationCode || user.companyId
                                    });
                                    return isSuccess(employeeResponse)
                                        ? [{ name: '全部员工', employeeNo: 'all' }].concat(employeeResponse.data || [])
                                        : [];
                                }}
                                selectProps={{
                                    placeholder: '请输入员工姓名',
                                    allowClear: true,
                                    labelInValue: true
                                }}
                                fieldsName={{
                                    value: 'employeeNo',
                                    title: 'name'
                                }}
                            />
                        )}
                    </Form.Item>
                </AdvancedSearch>
                <div>
                    <Table
                        rowKey="operateLogId"
                        columns={columns}
                        dataSource={dataSource}
                        loading={loading}
                        pagination={false}
                    />
                    <Pagination {...pagination} onChange={tablePageChange} />
                </div>
            </Card>
        </PageHeaderWrapper>
    );
};

export default withRoutePage(connect(({ user }) => ({ user: user.currentUser }))(Form.create()(Page)));
